package com.imooc.course.business.controller.admin;

import com.imooc.course.business.form.CategoryForm;
import com.imooc.course.business.form.PageForm;
import com.imooc.course.server.dto.CategoryDto;
import com.imooc.course.server.dto.PageDto;
import com.imooc.course.server.dto.ResponseDto;
import com.imooc.course.server.service.CategoryService;
import com.imooc.course.server.utils.CopyUtil;
import com.imooc.course.server.utils.ValidatorUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/admin/category")
public class CategoryController {

    private static final Logger log = LoggerFactory.getLogger(CategoryController.class);
    public static final String BUSINESS_NAME = "分类";


    @Resource
    private CategoryService categoryService;

    /**
     * 查询所有分类
     * @return
     */
    @PostMapping("/all")
    public ResponseDto getAll() {
        return ResponseDto.success().setContent(categoryService.getAll());
    }

    /**
     * 查询列表
     * @param pageForm 传入的page和size
     * @return
     */
    @PostMapping("/list")
    public ResponseDto getList(@RequestBody PageForm pageForm) {
        PageDto pageDto = CopyUtil.copy(pageForm, PageDto.class);
        categoryService.getList(pageDto);
        return ResponseDto.success().setContent(pageDto);
    }

    /**
     * 保存，id有值为更新，id无值为新增
     * @param categoryForm
     * @return
     */
    @PostMapping("/save")
    public ResponseDto addCategory(@RequestBody CategoryForm categoryForm) {
        //入参检查
        ValidatorUtil.notNull(categoryForm.getParent(), "父id");
        ValidatorUtil.notNull(categoryForm.getName(), "名称");
        ValidatorUtil.minimumToMaximum(categoryForm.getName(), "名称", 1, 50);

        CategoryDto categoryDto = CopyUtil.copy(categoryForm, CategoryDto.class);
        categoryService.save(categoryDto);
        return ResponseDto.success().setContent(categoryDto);
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    public ResponseDto del(@PathVariable String id) {
        categoryService.delete(id);
        return ResponseDto.success();
    }
}
